#include"Dictionary.h"

#include<iostream>
#include<fstream>
#include<sstream>
using std::ofstream;
using std::ifstream;
using std::cout;
using std::stringstream;
using std::istringstream;
Dictionary*Dictionary::pDic=nullptr;
Dictionary::Dictionary(){
    init("/home/zzh/cpp/project/v1_project/search/data/dict.dat","/home/zzh/cpp/project/v1_project/search/data/dictIndex.dat");
}

Dictionary*Dictionary::getInstance(){
    if(pDic==nullptr){
        pDic=new Dictionary();
    }
    return pDic;
}
    //根据文件路径初始化词典和索引表
void Dictionary::init(const string&dictpath,const string&indexTablepath){
    //导入词频统计
    ifstream ifs(dictpath);
    if(ifs.is_open()){
            cout<<"file open success!\n";
        }else{
            perror("file open fail\n");
            return;
        }
        //读入整个文本文件
        stringstream buf;
        buf<<ifs.rdbuf();
        string line;
        string word;
        int count;
        while(getline(buf,line)){
            istringstream iss(line);
            iss>>word>>count;
            _dict.push_back({word,count});
        }
        //放入_dict
        ifs.close();
        //导入索引
        ifs.open(indexTablepath);
        if(ifs.is_open()){
            cout<<"file open success!\n";
        }else{
            perror("file open fail\n");
            return;
        }
        //读入整个文本文件
        buf.clear();
        buf<<ifs.rdbuf();
        while(getline(buf,line)){
            istringstream iss(line);
            int value=0;
            iss>>word;
            iss>>value;
            _indexTable[word].insert(value);
            while(iss>>value){
                _indexTable[word].insert(value);
            }
        }
}
    //获取词典
vector<pair<string,int>>& Dictionary::getDict(){
    return _dict;
}
    //获取索引表
map<string,set<int>>& Dictionary::getIndexTable(){
    return _indexTable;
}
